<!DOCTYPE html>
<html>
<head>
    <title>Ball Collision</title>
    <style>
        canvas {
            border: 1px solid black;
        }
    </style>
</head>
<body>
    <canvas id="myCanvas" width="400" height="400"></canvas>
    <script>
        // 获取canvas元素
        const canvas = document.getElementById('myCanvas');
        const ctx = canvas.getContext('2d');

        // 球的属性
        const balls = [];

        // 初始化小球数量和位置
        const numBalls = 5; // 设置小球数量
        for (let i = 0; i < numBalls; i++) {
            balls.push({
                x: Math.random() * (canvas.width - 40) + 20,
                y: Math.random() * (canvas.height - 40) + 20,
                radius: 20,
                color: `rgb(${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)}, ${Math.floor(Math.random() * 256)})`,
                speedX: Math.random() * 6 - 3,
                speedY: Math.random() * 6 - 3
            });
        }

        // 绘制球
        function drawBalls() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            balls.forEach(ball => {
                ctx.beginPath();
                ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2);
                ctx.fillStyle = ball.color;
                ctx.fill();
                ctx.closePath();
            });
        }

        // 更新球的位置
        function moveBalls() {
            balls.forEach(ball => {
                ball.x += ball.speedX;
                ball.y += ball.speedY;

                // 检测碰撞
                if (ball.x + ball.radius > canvas.width || ball.x - ball.radius < 0) {
                    ball.speedX = -ball.speedX;
                }
                if (ball.y + ball.radius > canvas.height || ball.y - ball.radius < 0) {
                    ball.speedY = -ball.speedY;
                }

                // 检测球与球之间的碰撞
                balls.forEach(otherBall => {
                    if (otherBall !== ball) {
                        const dx = ball.x - otherBall.x;
                        const dy = ball.y - otherBall.y;
                        const distance = Math.sqrt(dx * dx + dy * dy);
                        if (distance < ball.radius + otherBall.radius) {
                            // 发生碰撞,交换速度
                            const tempSpeedX = ball.speedX;
                            const tempSpeedY = ball.speedY;
                            ball.speedX = otherBall.speedX;
                            ball.speedY = otherBall.speedY;
                            otherBall.speedX = tempSpeedX;
                            otherBall.speedY = tempSpeedY;
                        }
                    }
                });
            });
        }

        // 动画循环
        function animate() {
            moveBalls();
            drawBalls();
            requestAnimationFrame(animate);
        }

        animate();
    </script>
</body>
</html>